const pool = require("../base/mysql").pool,
    moment = require('moment'),
    //projectService = require('../project/projectService'),
    thirdPartyMap = {};
thirdPartyMap.qq = require('./qq.js');
thirdPartyMap.weixin = require('./weixin.js');
thirdPartyMap.weibo = require('./weibo.js');
thirdPartyMap.itron = require('./itron.js');
thirdPartyMap.weixin_itron = require('./weixin_itron.js');
thirdPartyMap.shanghaiedu = require('./shanghaiedu.js');
thirdPartyMap.juhe = require('./juhe.js');
thirdPartyMap.kjrb = require('./kjrb.js');

const sql_updateUser_tmp = "update `user` set `userId`=? WHERE userId=?;",
    sql_updateUserLimit_tmp = "update `user_limit` set `userId`=? WHERE userId=?;",
    sql_addUser = "INSERT INTO `user`(`userId`,`nickname`,`firstLoginTime`,`lastLoginTime`)VALUES(?,?,?,?);",
    //sql_getUser = "SELECT * FROM `user` where userId=? limit 1;",
    sql_updateUser = "UPDATE `user` SET `nickname` = ?, `lastLoginTime` = ? WHERE userId=?;",
    sql_addUserLimit = "INSERT INTO `user_limit`(`userId`,`projNum`)VALUES(?,?);",
    sql_getUserLimit = "SELECT `projNum` FROM `user_limit` where userId=? limit 1;",
    sql_updateUserLimit = "UPDATE `user_limit` SET `projNum` = ? WHERE userId=?;",
    sql_delUserPermission = "delete from  user_permission  where userId=?",
    sql_getUserPermission = "select permissionType from user_permission where userId=? ",
    sql_setUserOpts = "INSERT INTO `user_options`(`userId`,`theme`)VALUES(?,?);", //添加主题
    sql_updateUserOpts = "update `user_options` set `theme`=? WHERE userId=?;", //更新主题
    sql_getUserOpts = "select * from user_options where userId=? limit 1;"; //获取主题

// sql_getUserPermission = "select count(*) as count from user_permission where userId=? and permissionType=?";

const host_utype = {
    "testeditor.noatin.com": "juhe_",
    "editor.noatin.com": "juhe_",
    "teditor.noatin.com": "kjrb_"
};

//根据域名的不同获得不同用户
const getUserIdByHost = (host, uid) => {
    var utype = host_utype[host];
    if (!utype) {
        utype = "juhe_";
    }
    return utype + uid;
};

//更新用户权限
const updateUserPermission = (userId, permissionTypes, cb) => {
    // console.log(permissionTypes);
    var ret;
    var args = [userId];
    pool.query(sql_delUserPermission, args, (err) => {
        if (err) {
            console.error(err);
            ret = {
                result: -1,
                msg: "设置用户权限失败"
            };
            cb(ret);
        } else if (permissionTypes.length > 0) {
            var str = "";
            for (var i = 0; i < permissionTypes.length; i++) {
                str += "('" + userId + "','" + permissionTypes[i] + "'),";
            }
            str = str.substr(0, str.length - 1);
            //			 console.log(str);
            var sql_addUserPermission = "insert into user_permission(userId,permissionType) values " + str;
            pool.query(sql_addUserPermission, (err) => {
                if (err) {
                    console.error(err);
                    ret = {
                        result: -1,
                        msg: "设置用户权限失败"
                    };
                } else {
                    ret = {
                        result: 0,
                        msg: "设置用户权限成功"
                    };
                }
                cb(ret);
            });
        } else {
            ret = {
                result: 0,
                msg: "设置用户权限成功"
            };
            cb(ret);
        }
    });
};

//获取权限 admin代表管理员权限，DEPLOY_COURSE|代表发布普通课程权限,OFFLINE_COURSE|代表线下课程权限，DISPARK_COURSE发布开放课程权限
const getUserPermission = (userId, cb) => {
    pool.query(sql_getUserPermission, [userId], (err, rows) => {
        if (err) {
            console.error(err);
            cb(false);
        } else {
            // cb(rows[0].count > 0);
            var permissionTypes = [];
            for (let i in rows) {
                permissionTypes.push(rows[i].permissionType);
            }
            cb(permissionTypes);
        }
    });
};

//更新旧用户信息 临时接口
const updateUser_tmp = (userInfo) => {
    var oldUserId = userInfo.oldUserId,
        userId = userInfo.id,
        args = [userId, oldUserId];
    pool.query(sql_updateUser_tmp, args, (err, result) => {
        if (err) {
            console.error(err);
        }
    });
};

//更新旧用户工程限制信息 临时接口
const updateUserLimit_tmp = (userInfo) => {
    var oldUserId = userInfo.oldUserId,
        userId = userInfo.id,
        args = [userId, oldUserId];
    pool.query(sql_updateUserLimit_tmp, args, (err, result) => {
        if (err) {
            console.error(err);
        }
    });
};

//用户表操作
const addUser = (userInfo) => {
    var userId = userInfo.id,
        nickname = userInfo.nickname,
        firstLoginTime = moment().format('YYYY-MM-DD HH:mm:ss'),
        lastLoginTime = firstLoginTime,
        args = [userId, nickname, firstLoginTime, lastLoginTime];
    pool.query(sql_addUser, args, (err, result) => {
        if (err) {
            console.error(err);
        }
    });
};

// function getUser(userId) {
//     var args = [userId];
//     pool.query(sql_getUser, args,   (err, rows, fields) =>{
//       console.error(err);
//         if (rows.length > 0) {} else {}
//     });
// };

const updateUser = (userInfo) => {
    var userId = userInfo.id,
        nickname = userInfo.nickname,
        lastLoginTime = moment().format('YYYY-MM-DD HH:mm:ss'),
        args = [nickname, lastLoginTime, userId];
    pool.query(sql_updateUser, args, (err, result) => {
        if (err) {
            console.error(err);
        } else if (result.affectedRows < 1) {
            addUser(userInfo);
        }
    });
};

const addUserLimit = (userLimitInfo) => {
    var userId = userLimitInfo.userId,
        projNum = userLimitInfo.projNum,
        args = [userId, projNum];
    pool.query(sql_addUserLimit, args, (err, result) => {
        if (err) {
            console.error(err);
        }
    });
};

const getUserLimit = (userId, cb) => {
    var args = [userId];
    pool.query(sql_getUserLimit, args, (err, rows, fields) => {
        if (err) {
            cb(20);
            console.error(err);
        } else if (rows.length > 0) {
            cb(rows[0].projNum);
        } else {
            cb(20);
        }
    });
};

const updateUserLimit = (userLimitInfo) => {
    var userId = userLimitInfo.userId,
        projNum = userLimitInfo.projNum,
        args = [projNum, userId];
    pool.query(sql_updateUserLimit, args, (err, result) => {
        if (err) {
            console.error(err);
        } else if (result.affectedRows < 1) {
            addUserLimit(userLimitInfo)
        }
    });
};

const setUserState = (req, userInfo, cb) => {
    var ret;
    if (userInfo === null) {
        delete req.session.userInfo;
        // req.session.userInfo = null;
        // req.session.destroy(cb(0, null));
        ret = {
            result: 0,
            msg: "退出成功"
        }
        cb(ret);
    } else {
        let thirdParty = thirdPartyMap[userInfo.userType];
        if (thirdParty && thirdParty.login) {
            var cb2 = (ret2) => {
                if (ret2.result === 0) {
                    req.session.userInfo = ret2.msg;
                    //刷新用户数据
                    if (ret2.msg.oldUserId) {
                        updateUser_tmp(ret2.msg);
                        updateUserLimit_tmp(ret2.msg);
                        require('../project/projectService').updateProject_tmp(ret2.msg);
                    }
                    updateUser(ret2.msg);
                }
                cb(ret2);
            };
            thirdParty.login(userInfo, cb2);
        } else {
            console.error("setUserState找不到渠道，无法设置登录状态\n" + userInfo);
            delete req.session.userInfo;
            ret = {
                result: -1,
                msg: "登陆失败"
            }
            cb(ret);
        }
    }
};

const getUserState = (req, res) => {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo;
    if (!userInfo) {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    } else {
        getUserOptsAsync(userInfo.id).then((result) => {
            delete result[0].userId;
            userInfo.userOpts = result[0];
            res.send(JSON.stringify({
                result: 0,
                userInfo: userInfo
            }));
        });
    }
};

const setToken = (req, res) => {
    var channelName = req.params.channel,
        channel = thirdPartyMap[channelName];
    if (channel && channel.setToken) {
        channel.setToken(req, res, (userInfo) => {
            updateUser(userInfo);
        });
    } else {
        console.error("setToken找不到渠道\n" + req.params);
        res.send();
    }
};

const getToken = (req, res) => {
    var channelName = req.params.channel,
        channel = thirdPartyMap[channelName];
    if (channel && channel.getToken) {
        channel.getToken(req, res);
    } else {
        console.error("getToken找不到渠道\n" + req.params);
        res.send();
    }
};

//通过第三方的code去登录 支持那些从第三方网站带code参数的登录方式
let codeLogin = (req, res) => {
    var channelName = req.params.channel,
        channel = thirdPartyMap[channelName];
    if (channel && channel.codeLogin) {
        channel.codeLogin(req, res, (userInfo) => {
            updateUser(userInfo);
        });
    } else {
        console.error("setToken找不到渠道\n" + req.params);
        res.send();
    }
};
//换肤
const setUserOpts = (userId, userOpts) => {
    pool.query(sql_updateUserOpts, [userOpts.theme, userId], (err, rows) => {
        if (err) {
            console.error(err);
        } else if (rows.affectedRows < 1) {
            pool.query(sql_setUserOpts, [userId, userOpts.theme]);
        }
    });
};

async function getUserOptsAsync(userId) {
    return await new Promise((resolve, reject) => {
        pool.query(sql_getUserOpts, [userId], (err, rows) => {
            if (err) {
                console.error(err);
                reject(err);
            } else {
                resolve(rows.length > 0 ? rows : [{}]);
            }
        });
    })
};

module.exports = {
    codeLogin,
    getToken,
    getUserState,
    setUserState,
    updateUser,
    getUserLimit,
    updateUserLimit,
    updateUserPermission,
    getUserPermission,
    getUserIdByHost,
    setUserOpts
}